package cc.linker.steplink.crm.commons.oss;

import cc.linker.steplink.crm.commons.model.OssProperties;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.BucketInfo;
import com.aliyun.oss.model.CannedAccessControlList;

import java.util.List;

public class BucketOperations {
	private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;

	public BucketOperations(OssProperties oss) {
		this.endpoint = oss.getEndpoint();
		this.accessKeyId = oss.getAccessKeyId();
		this.accessKeySecret = oss.getAccessKeySecret();
	}

	/**
     * 创建Bucket
     * @param bucketName
     */
	public void create(String bucketName){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		// 创建bucket
		ossClient.createBucket(bucketName);

		// 关闭client
		ossClient.shutdown();
	}
	/**
	 * 列举Bucket
	 * @return
	 */
	public List<Bucket> list(){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		// 列举bucket
		List<Bucket> buckets = ossClient.listBuckets();
		for (Bucket bucket : buckets) {
		    System.out.println(" - " + bucket.getName());
		}

		// 关闭client
		ossClient.shutdown();
		return buckets;
	}
	/**
	 * 获取Bucket信息
	 * @return
	 */
	public BucketInfo getInfo(String bucketName){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		BucketInfo info = ossClient.getBucketInfo(bucketName);
		// Location
		info.getBucket().getLocation();
		// 创建日期
		info.getBucket().getCreationDate();
		// owner
		info.getBucket().getOwner();
		// 权限
		info.getGrants();

		// 关闭client
		ossClient.shutdown();
		return info;
	}
	/**
	 * 删除Bucket
	 * @param bucketName
	 */
	public void delete(String bucketName){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		// 删除bucket
		ossClient.deleteBucket(bucketName);

		// 关闭client
		ossClient.shutdown();
	}
	/**
	 * 判断Bucket是否存在
	 * @param bucketName
	 * @return
	 */
	public boolean exist(String bucketName){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		boolean exists = ossClient.doesBucketExist(bucketName);

		// 关闭client
		ossClient.shutdown();
		return exists;
		
	}
	/**
	 * 设置Bucket ACL Bucket的ACL包含三类：Private（私有读写）, PublicRead（公共读私有写）, PublicReadWrite（公共读写）
	 * @param bucketName
	 */
	public void setACL(String bucketName, CannedAccessControlList acl){
		// 创建OSSClient实例
		OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);

		// 设置bucket权限
		ossClient.setBucketAcl(bucketName,acl);

		// 关闭client
		ossClient.shutdown();
	}
	
}
